import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
  RouteRecordRaw,
} from "vue-router";
import path from 'path';
import { defineAsyncComponent, Component } from "vue";
import NProgress from "nprogress";
// --手动注册路由组件
// 非懒加载
import Index from "../views/Index.vue";
import test from "../views/test.vue";
import Parser from "../views/parser.vue";
import directives from "../views/directives.vue";
import AVT from "../views/AVT.vue";
// 懒加载
// const routes = [
//   { path: "/", component: Index },
//   { path: "/test", component: test },
//   { path: "/parser", component: Parser },
//   { path: "/demo", component: directives },
//   { path: "/avt", component: AVT },
// ];
// 异步组件
// const routes = [
//     { path: '/', component: defineAsyncComponent(()=>import('../views/Index.vue')) },
//     { path: '/test', component: defineAsyncComponent(()=>import('../views/test.vue')) },
//     { path: '/parser',component:defineAsyncComponent(()=>import('../views/Parser.vue')) },
//     {path:'/demo',component:defineAsyncComponent(()=>import('../views/directives.vue'))}
// ];

// --自动注册路由组件

// 获取views目录下的所有.vue文件
// 动态导入所有位于views目录下的Vue文件作为路由组件
const viewModules = import.meta.glob('../views/*.vue');

const routes: Array<RouteRecordRaw> = Object.keys(viewModules).map((path) => {
  // 获取路由路径
  const name = path.match(/\.\/views\/(.+)\.vue$/)![1];
  // 创建路由记录
  return {
    path: `/${name.toLowerCase()}`,
    name: name,
    component: viewModules[path] as any, // 这里需要断言类型，因为import.meta.glob返回的是个异步组件
  };
});
console.log(routes);
// 添加默认路由
routes.push({
  path: '/',
  redirect: '/index' // 假设Index.vue是首页组件
});
const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from , next) => {
  // 每次切换页面时，调用进度条
  NProgress.start();

  // 这个一定要加，没有next()页面不会跳转的。这部分还不清楚的去翻一下官网就明白了
  next();
});
router.afterEach(() => {  
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})
export default router;
